package com.cgwx.controller;

import com.alibaba.fastjson.JSONObject;
import com.cgwx.Utils.result.ResultUtil;
import com.cgwx.aop.GetUserInfo;
import com.cgwx.common.utils.PageUtil;
import com.cgwx.config.BusinessException;
import com.cgwx.config.SuppressResponseLog;
import com.cgwx.data.dto.NpjFileFolder;
import com.cgwx.data.dto.UserInfo;
import com.cgwx.data.dto.UserRoomDto;
import com.cgwx.entity.*;
import com.cgwx.mapper.AuthorityMapper;
import com.cgwx.mapper.UserRoomMapper;
import com.cgwx.service.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "共享空间")
@RequestMapping("/company")
@Slf4j
public class CompanyController {
    @Resource
    private IAuthorityService authorityService;
    @Resource
    private IFolderService folderService;
    @Resource
    private IFileService fileService;
    @Resource
    private IFavoritesService favoritesService;
    @Resource
    private IRoomService roomService;
    @Resource
    private IUtilService utilService;
    @Resource
    private IPersonalRecycleBinService personalRecycleBinService;
    @Resource
    private IUserService userService;
    @Resource
    private IDownloadService downloadService;
    @Resource
    private IUserRoomService userRoomService;
    @Resource
    private AuthorityMapper authorityMapper;
    @Resource
    private UserRoomMapper userRoomMapper;

    @GetMapping("/hello")
    @SuppressResponseLog
    @ApiOperation("测试打通")
    public Object hello() {
        log.info("hello123");
        return ResultUtil.success("hello");
    }

    @GetMapping("/getUsedSpace")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取已占用空间大小（单位是MB")
    public Object getUsedSpace(UserInfo userInfo, String type) {
        String result = roomService.getUsedSpace(userInfo.getUserId(), type);
        return ResultUtil.success(result);
    }

    @GetMapping("/getFolderTree")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取空间文件树")
    public Object getFolderTree(UserInfo userInfo, String visibility, @RequestParam String type) {
        Room room = roomService.getRoom(userInfo.getUserId(), userInfo.getDeptId(), type);
        List<Folder> result = folderService.getFolderTree(userInfo.getUserId(), userInfo.getDeptId(), room.getId(), type, visibility);
        return ResultUtil.success(result);
    }

    @GetMapping("/OpenFolder")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("打开文件夹")
    public Object OpenFolder(UserInfo userInfo, @RequestParam String entityId, @RequestParam String type, String visibility, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        List<FileFolder> fileFolders = folderService.OpenFolder(userInfo.getUserId(), userInfo.getDeptId(), entityId, keyword, type, column, sort, visibility);
        PageUtil<FileFolder> page = new PageUtil<FileFolder>().getPage(fileFolders.size(), pageSize, pageNum - 1);
        page.setList(page.startPage(fileFolders.size(), pageNum, pageSize, fileFolders));
        String authority = authorityService.checkAuthority(userInfo.getUserId(), userInfo.getDeptId(), entityId);
        return ResultUtil.success(page, authority);
    }

    @GetMapping("/checkAuthority")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取员工的单个文件（夹）权限")
    public Object checkAuthority(UserInfo userInfo, @RequestParam String entityId) {
        String authority = authorityService.checkAuthority(userInfo.getUserId(), userInfo.getDeptId(), entityId);
        if (authority.equals("0")) return ResultUtil.error(200, "无权限!");
        else return ResultUtil.success(authority);
    }

    @GetMapping("/checkAuthorityString")
    @SuppressResponseLog
    @ApiOperation("获取员工的单个文件（夹）权限")
    public Object checkAuthorityString(@RequestParam String account, @RequestParam String entityId) {
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userService.getUser(user).get(0);
        return authorityService.checkAuthority(account, user.getDeptId(), entityId);
    }

    @GetMapping("/getMemberAuthority")
    @GetUserInfo
    @ApiOperation("获取成员及权限")
    public Object getMemberAuthority(UserInfo userInfo, @RequestParam String entityId) {
        List<AuthorityInfo> authorityInfos = authorityService.getMemberAuthority(userInfo.getUserId(), userInfo.getDeptId(), entityId);
        Authority authority = new Authority();
        String info = "dept";
        authority.setPermissionType("company");
        authority.setEntityId(entityId);
        if(!authorityService.getAuthority(authority).isEmpty()) info = "company";
        return ResultUtil.success(authorityInfos, info);
    }

    @PostMapping("/insertMember")
    @GetUserInfo
    @ApiOperation("添加成员")
    public Object insertMember(UserInfo userInfo, @RequestBody Map<String, Object> requestBody) {
        String entityId = (String) requestBody.get("entityId");
        List<Map<String, String>> depts = (List<Map<String, String>>) requestBody.get("proxyDept");
        List<Map<String, String>> ids = (List<Map<String, String>>) requestBody.get("proxyId");
        return ResultUtil.success(authorityService.insertMember(userInfo.getUserId(), userInfo.getDeptId(), entityId, depts, ids));
    }

    @PostMapping("/updateMemberAuthority")
    @GetUserInfo
    @ApiOperation("修改成员权限")
    public Object updateMemberAuthority(UserInfo userInfo, @RequestParam String entityId, @RequestBody Map<String, Object> requestBody, @RequestParam String level) {
        List<Map<String, String>> depts = (List<Map<String, String>>) requestBody.get("proxyDept");
        List<Map<String, String>> ids = (List<Map<String, String>>) requestBody.get("proxyId");
        String result = authorityService.updateAuthority(userInfo.getUserId(), userInfo.getDeptId(), entityId, depts, ids, level);
        return ResultUtil.success(result);
    }

    @PostMapping("/deleteAuthority")
    @GetUserInfo
    @ApiOperation("移除成员权限")
    public Object deleteAuthority(UserInfo userInfo, @RequestParam String entityId, @RequestParam String id, @RequestParam String type) {
        String result = authorityService.deleteAuthority(userInfo.getUserId(), userInfo.getDeptId(), entityId, id, type);
        if(result.equals("移除权限成功!")) return ResultUtil.success(result);
        else return ResultUtil.error(200, result);
    }

    @GetMapping("/insertFolder")
    @GetUserInfo
    @ApiOperation("新建文件夹")
    public Object insertFolder(UserInfo userInfo, @RequestParam String entityName, @RequestParam String parentId, @RequestParam String type) {
        String account = userInfo.getUserId();
        String userName = userInfo.getUserName();
        String deptId = userInfo.getDeptId();
        Folder folder = new Folder();
        folder.setEntityId(parentId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        String result = folderService.insertFolder(account, userName, deptId, roomId, entityName, parentId, type);
        return ResultUtil.success(result);
    }

    @PostMapping("/uploadFile")
    @GetUserInfo
    @ApiOperation("上传文件")
    public Object uploadFile(UserInfo userInfo, @RequestParam String parentId, @RequestParam MultipartFile multipartFile, @RequestParam String type) {
        Folder folder = new Folder();
        folder.setEntityId(parentId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        String result = utilService.uploadFile(userInfo.getUserId(), userInfo.getUserName(), userInfo.getDeptId(), roomId, parentId, type, multipartFile, "false");
        return ResultUtil.success(result);
    }

    @GetMapping("/getDownload")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取下载队列")
    public Object getDownload(UserInfo userInfo, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Download> downloads = downloadService.getDownload(userInfo.getUserId(), keyword, column, sort);
        return ResultUtil.success(new PageInfo<>(downloads));
    }

    @GetMapping("/deleteDownload")
    @GetUserInfo
    @ApiOperation("删除下载队列")
    public Object deleteDownload(UserInfo userInfo, String ids) {
        List<String> idList = JSONObject.parseArray(ids, String.class);
        String result;
        for(String id: idList){
            result = downloadService.deleteDownload(id);
            if(result.equals("删除失败!")) return ResultUtil.error(200, "删除失败!");
        }
        return ResultUtil.success("删除成功!");
    }

    @GetMapping("/downloadFile")
    @GetUserInfo
    @ApiOperation("下载单个文件")
    public Object downloadFile(UserInfo userInfo, @RequestParam String entityId, @RequestParam String type) {
        String Url = utilService.getURLByFileId(userInfo.getUserId(), userInfo.getDeptId(), entityId, type);
        if(Url.startsWith("http")) return ResultUtil.success(Url);
        else return ResultUtil.error(200, Url);
    }

    @GetMapping("/downloadFiles")
    @GetUserInfo
    @ApiOperation("下载文件")
    @Transactional
    public Object downloadFiles(UserInfo userInfo, @RequestParam String entityIds, @RequestParam String type) throws JsonProcessingException {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        if(entityIdList.size() == 1){
            Folder folder = new Folder();
            folder.setEntityId(entityIdList.get(0));
            folder = folderService.getFolder(folder).get(0);
            String id = downloadService.insertDownload(userInfo.getUserId(), folder.getEntityName(), utilService.getPathName(folder.getEntityId()));
            List<FileFolder> fileFolders = utilService.downloadFolder(userInfo.getUserId(), userInfo.getDeptId(), folder.getEntityId(), type);
            if(fileFolders == null || fileFolders.isEmpty()) throw new BusinessException("无下载权限!");
            else utilService.download(userInfo, fileFolders, folder.getEntityName(), id);
        }
        else if(entityIdList.size() > 1){
            String oneEntityId = entityIdList.get(0);
            String parentPath;
            String name;
            if(oneEntityId.startsWith("folder")){
                Folder folder = new Folder();
                folder.setEntityId(oneEntityId);
                folder = folderService.getFolder(folder).get(0);
                parentPath = utilService.getPathName(folder.getParentId());
                name = folder.getEntityName()+ "等文件";
            }
            else {
                File file = new File();
                file.setEntityId(oneEntityId);
                file = fileService.getFile(file).get(0);
                parentPath = utilService.getPathName(file.getParentId());
                name = file.getEntityName()+ "等文件";
            }
            String id = downloadService.insertDownload(userInfo.getUserId(), name, parentPath);
            List<FileFolder> fileFolders = new ArrayList<>();
            FileFolder fileFolder = new FileFolder();
            fileFolder.setEntityName(name);
            for(String entityId : entityIdList){
                List<FileFolder> oneFileFolders;
                if(entityId.startsWith("folder")){
                    oneFileFolders = utilService.downloadFolder(userInfo.getUserId(), userInfo.getDeptId(), entityId, type);
                    if(oneFileFolders == null || oneFileFolders.isEmpty()) throw new BusinessException("无下载权限!");
                }
                else{
                    if(!type.equals("staff") && !type.equals("me") && !type.equals("Me") && Integer.parseInt(authorityService.checkAuthority(userInfo.getUserId(), userInfo.getDeptId(), entityId)) < 2)  throw new BusinessException("无下载权限!");
                    oneFileFolders = new ArrayList<>();
                    File file = new File();
                    file.setEntityId(entityId);
                    file = fileService.getFile(file).get(0);
                    FileFolder fileFolder1 = new FileFolder(file);
                    oneFileFolders.add(fileFolder1);
                }
                List<FileFolder> fileFolders1 = fileFolder.getChildren();
                fileFolders1.addAll(oneFileFolders);
                fileFolder.setChildren(fileFolders1);
            }
            fileFolders.add(fileFolder);
            utilService.download(userInfo, fileFolders, name, id);
        }
        return ResultUtil.success("已加入打包队列! 您可以在个人空间的下载打包中心进行查看与下载。");
    }

    @GetMapping("/viewFile")
    @GetUserInfo
    @ApiOperation("预览文件")
    public Object viewFile(UserInfo userInfo, @RequestParam String entityId, @RequestParam String type) {
        String result = utilService.viewFile(userInfo.getUserId(), userInfo.getDeptId(), entityId, type);
        if(result.startsWith("http")) return ResultUtil.success(result);
        else return ResultUtil.error(200, result);
    }

    @GetMapping("/rename")
    @GetUserInfo
    @ApiOperation("重命名文件(夹)")
    public Object rename(UserInfo userInfo, @RequestParam String entityName, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.rename(userInfo.getUserId(), userInfo.getDeptId(), entityName, entityId, parentId, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/remove")
    @GetUserInfo
    @Transactional
    @ApiOperation("根据parentId移动个人文件（夹）")
    public Object remove(UserInfo userInfo, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.remove(userInfo.getUserId(), userInfo.getDeptId(), entityId, parentId, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/insertFavorites")
    @GetUserInfo
    @ApiOperation("收藏")
    public Object insertFavorites(UserInfo userInfo, @RequestParam String entityIds) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = favoritesService.insertFavorites(userInfo.getUserId(), entityIdList);
        return ResultUtil.success(result);
    }

    @GetMapping("/deleteFavorites")
    @GetUserInfo
    @ApiOperation("取消收藏")
    public Object deleteFavorites(UserInfo userInfo, @RequestParam String entityIds) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = favoritesService.deleteFavorites(userInfo.getUserId(), entityIdList);
        return ResultUtil.success(result);
    }

    @GetMapping("/getFavorites")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取我的收藏")
    public Object getFavorites(UserInfo userInfo, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Favorites> favorites = favoritesService.getFavorites(userInfo.getUserId(), userInfo.getDeptId(), keyword, column, sort);
        return ResultUtil.success(new PageInfo<>(favorites));
    }

    @GetMapping("/delete")
    @GetUserInfo
    @Transactional
    @ApiOperation("根据entityId删除文件（夹）")
    public Object delete(UserInfo userInfo, @RequestParam String entityIds, @RequestParam String type) {
        log.info("文件{}被删除，删除人:{}{}", entityIds, userInfo.getUserId(), userInfo.getUserName());
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = utilService.delete(userInfo.getUserId(), userInfo.getDeptId(), entityIdList, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/getRecycleBin")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取空间回收站")
    public Object getRecycleBin(UserInfo userInfo, String keyword, String roomId, @RequestParam String type, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        List<PersonalRecycleBin> result;
        if(type.equals("me") || type.equals("staff") || type.equals("Me")){
            roomId = roomService.getPersonalRoom(userInfo.getUserId());
            PageHelper.startPage(pageNum, pageSize);
            result = personalRecycleBinService.getAllPersonalRecycleBin(userInfo.getUserId(), roomId, keyword, column, sort);
        }
        else if(type.equals("dept")){
            String deptRoomId = roomService.getDeptRoom(userInfo.getUserId());
            PageHelper.startPage(pageNum, pageSize);
            result = personalRecycleBinService.getDeptRecycleBin(userInfo.getUserId(), userInfo.getDeptId(), deptRoomId, keyword, column, sort);
        }
        else if(type.equals("free")){
            PageHelper.startPage(pageNum, pageSize);
            result = personalRecycleBinService.getFreeRecycleBin(userInfo.getUserId(), userInfo.getDeptId(), roomId, keyword, column, sort);
        }
        else{
            String companyRoomId = roomService.getCompanyRoomId();
            PageHelper.startPage(pageNum, pageSize);
            result = personalRecycleBinService.getCompanyRecycleBin(userInfo.getUserId(), userInfo.getDeptId(), companyRoomId, keyword, column, sort);
        }
        return ResultUtil.success(new PageInfo<>(result));
    }

    @GetMapping("/restore")
    @GetUserInfo
    @Transactional
    @ApiOperation("根据entityId恢复文件（夹）")
    public Object restore(UserInfo userInfo, @RequestParam String entityIds, @RequestParam String type) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = utilService.restore(userInfo.getUserId(), userInfo.getDeptId(), entityIdList, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/removeRecycleBin")
    @GetUserInfo
    @Transactional
    @ApiOperation("从回收站移动到共享空间")
    public Object removeRecycleBin(UserInfo userInfo, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.removeRecycleBin(userInfo.getUserId(), userInfo.getDeptId(), entityId, parentId, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/deleteEntirely")
    @GetUserInfo
    @ApiOperation("彻底删除")
    public Object deleteEntirely(UserInfo userInfo, @RequestParam String entityIds, @RequestParam String type) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = personalRecycleBinService.deleteRecycleBinEntirelyById(entityIdList);
        if(!result.equals("彻底删除成功!")) throw new BusinessException("彻底删除失败!");
        return ResultUtil.success(result);
    }

    @GetMapping("/addTags")
    @GetUserInfo
    @ApiOperation("添加标签")
    public Object addTags(UserInfo userInfo, @RequestParam String entityId, @RequestParam String tags, @RequestParam String type) {
        List<String> tagList = JSONObject.parseArray(tags, String.class);
        String result = utilService.addTags(userInfo.getUserId(), userInfo.getDeptId(), entityId, tagList, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/addFreeRoom")
    @GetUserInfo
    @ApiOperation("新建自由空间")
    public Object addFreeRoom(UserInfo userInfo, @RequestParam String roomName, @RequestParam String accounts) {
        List<String> accountList = JSONObject.parseArray(accounts, String.class);
        String result = roomService.insertFreeRoom(userInfo.getUserId(), userInfo.getUserName(), roomName, accountList);
        return ResultUtil.success(result);
    }

    @GetMapping("/freeRoomInsertStaff")
    @GetUserInfo
    @ApiOperation("自由空间添加员工")
    public Object freeRoomInsertStaff(UserInfo userInfo, @RequestParam String entityId, @RequestParam String accounts) {
        List<String> accountList = JSONObject.parseArray(accounts, String.class);
        String result = userRoomService.freeRoomInsertStaff(userInfo.getUserId(), userInfo.getDeptId(), entityId, accountList);
        return ResultUtil.success(result);
    }

    @GetMapping("/freeRoomDeleteStaff")
    @GetUserInfo
    @ApiOperation("自由空间删除员工")
    public Object freeRoomDeleteStaff(UserInfo userInfo, @RequestParam String entityId, @RequestParam String accounts) {
        List<String> accountList = JSONObject.parseArray(accounts, String.class);
        String result = userRoomService.freeRoomDeleteStaff(userInfo.getUserId(), userInfo.getDeptId(), entityId, accountList);
        return ResultUtil.success(result);
    }

    @GetMapping("/getMyManageFreeRoomInfo")
    @GetUserInfo
    @ApiOperation("获取我管理的自由空间信息")
    public Object getMyManageFreeRoomInfo(UserInfo userInfo, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        return ResultUtil.success(new PageInfo<>(userRoomService.getMyManageFreeRoomInfo(userInfo.getUserId(), keyword, column, sort)));
    }

    @GetMapping("/getMyFreeRoomInfo")
    @GetUserInfo
    @ApiOperation("获取包含我的自由空间信息")
    public Object getMyFreeRoomInfo(UserInfo userInfo, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        return ResultUtil.success(new PageInfo<>(userRoomService.getMyFreeRoomInfo(userInfo.getUserId(), keyword, column, sort)));
    }

    @GetMapping("/getMyManageFreeRoom")
    @ApiOperation("获取我创建的自由空间")
    @Transactional
    @GetUserInfo
    public Object getMyManageFreeRoom(UserInfo userInfo) {
        Room room = new Room();
        room.setRoomId(userInfo.getUserId());
        room.setRoomType("free");
        List<Room> rooms = roomService.getRoom(room);
        return ResultUtil.success(rooms);
    }

    @GetMapping("/getMyFreeRoom")
    @ApiOperation("获取包含我的的自由空间")
    @Transactional
    @GetUserInfo
    public Object getMyFreeRoom(UserInfo userInfo) {
        UserRoom userRoom = new UserRoom();
        userRoom.setAccount(userInfo.getUserId());
        List<UserRoomDto> UserRoomDtos = userRoomMapper.getUserRoom(userRoom);
        return ResultUtil.success(UserRoomDtos);
    }

    @GetMapping("/getFreeRoomInfo")
    @ApiOperation("获取某自由空间信息")
    @Transactional
    @GetUserInfo
    public Object getFreeRoomInfo(UserInfo userInfo, @RequestParam String id) {
        List<UserRoomDto> userRooms = userRoomService.getUserRoomById(id);
        return ResultUtil.success(userRooms);
    }

    @GetMapping("/getFreeRoomTree")
    @ApiOperation("获取某自由空间文件树")
    @Transactional
    @GetUserInfo
    public Object getFreeRoomTree(UserInfo userInfo, @RequestParam String id) {
        List<Folder> folders = folderService.getFolderTree(userInfo.getUserId(), userInfo.getDeptId(), id, "company", "true");
        return ResultUtil.success(folders);
    }

    @GetMapping("/getAllMyManageFreeRoomTree")
    @ApiOperation("获取所有我创建的自由空间文件树")
    @Transactional
    @GetUserInfo
    public Object getAllFreeRoomTree(UserInfo userInfo) {
        Room room0 = new Room();
        room0.setRoomId(userInfo.getUserId());
        room0.setRoomType("free");
        List<Room> rooms = roomService.getRoom(room0);
        Folder folderRoot = new Folder();
        folderRoot.setEntityName("我创建的空间");
        folderRoot.setEntityId("1");
        for(Room room: rooms){
            List<Folder> folders = folderService.getFolderTree(userInfo.getUserId(), userInfo.getDeptId(), room.getId(), "company", "true");
            folders.get(0).setParentId(folderRoot.getEntityId());
            List<Folder> folders1 = folderRoot.getChildren();
            folders1.addAll(folders);
            folderRoot.setChildren(folders1);
        }
        return ResultUtil.success(folderRoot);
    }

    @GetMapping("/getAllMyFreeRoomTree")
    @ApiOperation("获取所有包含我的自由空间文件树")
    @Transactional
    @GetUserInfo
    public Object getAllMyFreeRoomTree(UserInfo userInfo) {
        UserRoom userRoom = new UserRoom();
        userRoom.setAccount(userInfo.getUserId());
        List<UserRoomDto> UserRoomDtos = userRoomMapper.getUserRoom(userRoom);
        Folder folderRoot = new Folder();
        folderRoot.setEntityName("包含我的空间");
        folderRoot.setEntityId("0");
        for(UserRoomDto room: UserRoomDtos){
            List<Folder> folders = folderService.getFolderTree(userInfo.getUserId(), userInfo.getDeptId(), room.getEntityRoom(), "company", "true");
            folders.get(0).setParentId(folderRoot.getEntityId());
            List<Folder> folders1 = folderRoot.getChildren();
            folders1.addAll(folders);
            folderRoot.setChildren(folders1);
        }
        return ResultUtil.success(folderRoot);
    }

    @GetMapping("/deleteFreeRoomById")
    @ApiOperation("解散自由空间")
    @Transactional
    @GetUserInfo
    public Object deleteFreeRoomById(UserInfo userInfo, @RequestParam String entityId, @RequestParam String id) {
        Room room = new Room();
        room.setId(id);
        room = roomService.getRoom(room).get(0);
        if(!userInfo.getUserId().equals(room.getRoomId())) throw new BusinessException("只有空间创建人可以解散空间!");
        if(!userRoomService.deleteUserRoomById(id)){
            log.error("deleteFreeRoomById: 空间成员删除失败!");
            throw new BusinessException("空间成员删除失败!");
        }
        if(!roomService.deleteFreeRoom(id)){
            log.error("deleteFreeRoomById: 空间删除失败!");
            throw new BusinessException("空间删除失败!");
        }
        List<String> fileFolders = authorityService.getChildrenAndMyself(entityId);
        Authority authority = new Authority();
        authority.setPermissionType("staff");
        for(String fileFolder : fileFolders) {
            authority.setEntityId(fileFolder);
            if(!authorityMapper.deleteAllAuthority(authority)){
                log.error("deleteFreeRoomById: 空间权限删除失败!");
                throw new BusinessException("空间权限删除失败!");
            }
            if(fileFolder.startsWith("folder")){
                if(!folderService.deleteFolderById(fileFolder).equals("删除成功!")){
                    log.error("deleteFreeRoomById: 文件夹删除失败!");
                    throw new BusinessException("文件夹删除失败!");
                }
            }
            else{
                if(!fileService.deleteFileById(fileFolder).equals("删除成功!")){
                    log.error("deleteFreeRoomById: 文件删除失败!");
                    throw new BusinessException("文件删除失败!");
                }
            }
        }
        return ResultUtil.success("自由空间解散成功!");
    }

    @GetMapping("/updateFreeRoomAuthById")
    @ApiOperation("自由空间权限批量管理")
    @Transactional
    @GetUserInfo
    public Object updateFreeRoomAuthById(UserInfo userInfo, @RequestParam String entityId, @RequestParam String id, @RequestParam String level) {
        Room room = new Room();
        room.setId(id);
        room = roomService.getRoom(room).get(0);
        room.setFreeAuth(level);
        if(!roomService.updateAuthRoomById(room).equals("更新成功!")){
            log.error("updateFreeRoomAuthById: 权限更新失败!");
            return ResultUtil.success("权限更新失败!");
        }
        else{
            List<String> fileFolders = authorityService.getChildrenAndMyself(entityId);
            Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
            for(String fileFolder: fileFolders){
                List<Authority> authorities = authorityService.getAuthority(userInfo.getUserId(), fileFolder);
                for(Authority authority: authorities){
                    if(!authority.getPermissionId().equals(userInfo.getUserId())){
                        authority.setAuthorityLevel(level);
                        authority.setUpdateTime(time);
                        authorityMapper.updateAuthority(authority);
                    }
                }
            }
            return ResultUtil.success("权限更新成功!");
        }
    }

    @GetMapping("/addFolderManager")
    @ApiOperation("某文件(夹)添加管理员(后台调用)")
    @Transactional
    @GetUserInfo
    public Object addFolderManager(UserInfo userInfo, @RequestParam String entityId, @RequestParam String account) {
        return authorityService.addFolderManager(entityId, account);
    }

    @GetMapping("/globalFileSearch")
    @ApiOperation("全局搜索")
    @Transactional
    @GetUserInfo
    public Object globalFileSearch(UserInfo userInfo, @RequestParam String globalKeyword, @RequestParam String type, String column, String sort, String visibility, @RequestParam int pageNum, @RequestParam int pageSize) {
        List<NpjFileFolder> npjFileFolders = folderService.globalFileSearch(userInfo.getUserId(), userInfo.getDeptId(), globalKeyword, visibility, type, column, sort);
        PageUtil<NpjFileFolder> page = new PageUtil<NpjFileFolder>().getPage(npjFileFolders.size(), pageSize, pageNum - 1);
        page.setList(page.startPage(npjFileFolders.size(), pageNum, pageSize, npjFileFolders));
        return ResultUtil.success(page);
    }
}